<template>
  <div class="login-container">
    <div class="login-box">
      <div class="title-box"></div>
      <!-- 登陆的表单区域 -->
       <el-form :model="loginForm" ref="loginFormRef" :rules="loginFormRules">
        <el-form-item prop="username">
          <el-input placeholder="请输入用户名" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入密码" v-model="loginForm.password" minlength="6" maxlength="15"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="loginFn">登录</el-button>
          <el-link type="info" @click="$router.push('/reg')">去注册</el-link>
        </el-form-item>
       </el-form>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRef: '',
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名必须是1-10的字母数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15的非空字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    loginFn () {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const { data: res } = await loginAPI(this.loginForm)
        if (res.code !== 0) {
          return this.$message.error(res.message)
        }
        this.$message.success(res.message)
        // 将token存入vuex中
        this.$store.commit('updateToken', res.token)
        this.$router.push('/')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container{
  background-image: url('@/assets/images/login_bg.jpg');
  height: 100%;
  background-size: cover;
  background-position: center;
  .login-box{
    width: 400px;
    height: 270px;
    background-color: #fff;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    padding: 0 30px;
    box-sizing: border-box;
    border-radius: 3px;
    .title-box{
      background-image: url('@/assets/images/login_title.png');
      background-repeat: no-repeat;
      height: 60px;
      background-position: center;
    }
    .login-btn{
      width: 100%;
    }
  }
}
</style>
